# -*- coding: utf-8 -*-
# @Time    : 2019/10/31 15:55
# @Author  : 岳保保
# @File    : AuthorityResponse.py.py
# @Software: PyCharm
from abc import ABC

from rest_framework import serializers

from crm.models import Authority, Role


class AuthoritySerializer(serializers.ModelSerializer):
    """权限序列化"""

    class Meta:
        model = Authority
        fields = "__all__"

    title = serializers.CharField(label="标题")
    type = serializers.CharField()
    url = serializers.CharField()
    code = serializers.CharField()

    levels = serializers.SerializerMethodField()

    def get_levels(self, obj):
        if obj.levels:
            parent_list = []
            for pk in obj.levels.split('/'):
                parent_list.append(Authority.objects.filter(pk=pk).first())

            return [{
                "id": authority.pk,
                "title": authority.title}
                for authority in parent_list]
        return None


class RoleSerializer(serializers.ModelSerializer):
    """角色序列化"""

    class Meta:
        model = Role
        fields = "__all__"

    name = serializers.CharField()
    type = serializers.IntegerField(source="get_type_display")
    # authority = models.ManyToManyField(to='Authority', verbose_name='角色所拥有的权限', blank=True)
